<template>
	<view class="container">
		<map id="myMap" class="map" :latitude="centerLat" :polyline="polyline" :longitude="centerLng" :markers="markers"
			show-location :zoom="zoom"></map>
		<view class="sliderpanel">
			<view class="contents">
				
			
			</view>
		</view>
	</view>
</template>

<script>
	import payment from '@/pageA/payment/index.vue'
	import {
		generateSignatureGet
	} from '@/utils/signature.js';
	import configData from '@/common/config.js'
	export default {
		components: {
			payment,
		},
		data() {
			return {
				centerLat: 0, // 初始纬度（可设为当前位置）
				centerLng: 0, // 初始经度
				markers: [], // 动态标记点
				TabCur: 0,
				labelstyle: {
					whiteSpace: 'nowrap',
					fontWeight: 'bold',
					textIndent: '20rpx'
				},
				distance: 0,
				take: {},
				close: {},
				addressId: undefined,
				addressType: undefined,
				zoom: 14,
				polyline: [],
				mapKey: configData.MapKey,
				// 完整路线点数组
				routePoints: [],
				// 路线总距离
				totalDistance: 0,
				// 路线总时间
				totalTime: 0,
				mapContext: null,

				orderNumber: undefined,
				payList: {},
				minPoint: {}, //距离发货地最近的快递柜位置
				pointList: [],
			}
		},
		onLoad() {
			this.getUserLocation(); // 获取用户初始位置
			
		},
		onShow(option) {
			this.addressId = uni.getStorageSync('addressId')
			this.addressType = uni.getStorageSync('addressType')
			if (this.addressId) {
				this.getAddress(this.addressId)
				uni.removeStorageSync('addressType')
				uni.removeStorageSync('addressId')
			}
		},
		methods: {
			tabSelect(e) {
				this.TabCur = e.currentTarget.dataset.id;
			},
			
			// 跳转发货地址
			bindtake(e) {
				uni.navigateTo({
					url: '/pages/takeaddress/takeaddress?addressType=' + e
				})
			},


		




			//获取距离发货地址最近的快递柜位置
			getMinDistancePoint() {
				//获取快递柜列表
				this.$Request.getT('/app/point/list', {
					type: 0,
					area: this.take.address
				}).then(it => {
					if (it.code == 0) {
						this.pointList = it.data
						this.$Request.postJson(
							`/app/point/getMinDistancePoint?lat=${this.take.addressLatitude}&lng=${this.take.addressLongitude}`,
							this.pointList).then(res => {
							if (res.code == 0) {
								this.minPoint = res.data
								this.binddistance()
							}
						});
					}
				})
			},




			// 距离计算
			binddistance() {
				
				let ol = this.minPoint.lat
				let od = this.minPoint.lng
				let dl = this.close.addressLatitude
				let dd = this.close.addressLongitude
				this.$Request.postT('/app/indent/distance?ol=' + ol + '&od=' + od + '&dl=' + dl + '&dd=' + dd).then(
					res => {
						if (res.code === 0) {
							this.distance = res.data
						}
					}
				);
			},
			
			
			// 计算两点间距离（米）
			calculateDistance(lat1, lng1, lat2, lng2) {
				const radLat1 = lat1 * Math.PI / 180.0;
				const radLat2 = lat2 * Math.PI / 180.0;
				const a = radLat1 - radLat2;
				const b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
				let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
				s = s * 6378.137; // EARTH_RADIUS
				s = Math.round(s * 10000) / 10;
				return s;
			},
			




			// 计算路线
			calculateRoute() {
				// 清空旧路线
				this.polyline = [];

				// 调用路线规划API
				this.$nextTick(() => {
					const path = '/ws/direction/v1/driving';
					const params = {
						key: this.mapKey,
						from: `${this.take.addressLatitude},${this.take.addressLongitude}`,
						to: `${this.close.addressLatitude},${this.close.addressLongitude}`,
						waypoints: ``,
					};
					const sk = configData.SecretKey;
					const sig = generateSignatureGet(path, params, sk);
					params.sig = sig;
					const url = `https://apis.map.qq.com${path}?${this.encodeParams(params)}`;

					uni.request({
						url: url,
						success: (res) => {
							if (res.statusCode === 200) {
								// 修正数据路径（根据实际返回结构调整）
								this.handleRouteSuccess(res.data)
							}
						},
						fail: (err) => {
							console.log(err);
						}
					});
				})
			},

			encodeParams(params) {
				return Object.entries(params)
					.map(([key, value]) => {
						return `${key}=${encodeURIComponent(value)}`
					})
					.join('&')
			},


			// 路线规划成功回调
			handleRouteSuccess(res) {
				if (!res.result || !res.result.routes || res.result.routes.length === 0) {
					uni.showToast({
						title: '未找到可行路线',
						icon: 'none'
					});
					return;
				}

				const route = res.result.routes[0];
				const coors = route.polyline;
				const kr = 1000000; // 压缩系数

				// 坐标解压算法
				for (let i = 2; i < coors.length; i++) {
					coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
				}

				// 生成路径点数组
				const points = [];
				for (let i = 0; i < coors.length; i += 2) {
					points.push({
						latitude: coors[i],
						longitude: coors[i + 1]
					});
				}

				// 保存路线点用于导航
				this.routePoints = points;

				// 更新路线数据
				this.polyline = [{
					points: points,
					color: '#367EEF',
					width: 6,
					borderWidth: 2,
					borderColor: '#5B98FD',
					arrowLine: true
				}];

				// 保存路线信息
				this.totalDistance = route.distance || 0;
				this.totalTime = route.duration || 0;
				console.log('points', points);
				// 自动调整视野
				this.mapContext.includePoints({
					points: points,
					padding: [40, 40, 40, 40]
				});

				// 更新距离和时间显示
				// this.updateRouteInfo();
			},



			// 获取用户当前位置
			getUserLocation() {
				// 创建地图上下文
				this.mapContext = uni.createMapContext('myMap', this);
				uni.getLocation({
					type: 'gcj02', // 腾讯地图使用国测局坐标系
					success: (res) => {
						this.centerLat = res.latitude;
						this.centerLng = res.longitude;
						// this.addCenterMarker(); // 添加中心图标
					},
					fail: (err) => {
						console.error('获取位置失败:', err);
					}
				});
			},
			// 添加中心图标
			addCenterMarker(data, title, type) {
				const addressList = {
					id: data.addressId,
					latitude: data.addressLatitude,
					longitude: data.addressLongitude,
					iconPath: '../../static/my/add.png', // 图标路径
					width: 28,
					height: 30,
					callout: {
						content: title,
						color: '#000',
						fontSize: 14,
						borderRadius: 6, // 圆角
						padding: 5,
						display: 'ALWAYS' // 气泡始终显示
					}
				}
				this.markers[type] = addressList
				if (this.markers.length == 1) {
					this.centerLat = data.addressLatitude;
					this.centerLng = data.addressLongitude;
				}
			},
			// 监听地图区域变化（实时获取中心点）
			onRegionChange(e) {
				const center = e.detail?.centerLocation || {};
				if (center.latitude && center.longitude) {
					this.centerLat = center.latitude;
					this.centerLng = center.longitude;
				}
				this.addCenterMarker();
			},
		},
	}
</script>

<style scoped lang="scss">
	.container {
		position: relative;
		max-height: 100vh;
		overflow: hidden;

		.map {
			width: 100%;
			height: 38vh;
		}

		.bor-cor {
			border-bottom: 4rpx solid #f37b1d;
			// border-top: 4rpx solid #f37b1d;
			// border-radius: 100rpx;
		}

		.sliderpanel {
			width: 100%;
			height: 65vh;
			position: fixed;
			left: 0;
			bottom: 0;
			background-color: #fff;
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;
			z-index: 99;
		}
	}

	.one_box {
		width: 100%;
		/* height: 80upx; */
		/* background: #F5F5F5; */
		margin: 0 auto;
		border-radius: 12upx;
		display: flex;
		/* height: 100rpx; */
		align-items: center;
	}

	.box_dian {
		/* flex: 1; */
		width: 10%;
		display: flex;
		justify-content: center;
		align-items: center;

	}

	.box_dian image {
		width: 45rpx;
		height: 45rpx;
	}

	.box_name {
		flex: 5;
		display: flex;
		justify-content: left;
		align-items: center;
		color: #333333;
		font-weight: 700;
	}

	.box_addres {
		/* flex: 5; */
		width: 80%;
		font-size: 32rpx;
		overflow: hidden;
	}

	.box_addres1 {
		/* flex: 5; */
		width: 80%;
		font-size: 28rpx;
		overflow: hidden;
	}

	.box_jh {
		margin-left: 19rpx;
		height: 30rpx;
		display: flex;
		justify-content: left;
		align-items: center;
	}

	.box_jh image {
		width: 30upx;
		height: 30upx;
	}

	.contents {
		width: 100%;
		/* #ifdef MP-WEIXIN */
		margin-top: 25rpx;
		/* #endif */
	}

	.part_one {
		width: 95%;
		margin: 0 auto;
		/* height: 240upx; */
		background: #ffffff;
		border-radius: 20upx;
		margin-top: 20upx;
		padding: 25rpx 10rpx;
	}
</style>